package com.chuenyee.config;

import com.chuenyee.service.FileServerImpl;
import com.chuenyee.until.ConfigUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.security.Principal;

@Configuration
@EnableResourceServer
@RestController
public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {
    Logger logger = LoggerFactory.getLogger(ResourceServerConfiguration.class);

    @Value("${chuenyee.public-key}")
    private String publicKey;

    @Override
    public void configure(HttpSecurity http) throws  Exception{
         http.authorizeRequests().antMatchers("/**").authenticated();
    }

    @Override
    public void configure(ResourceServerSecurityConfigurer resource) throws  Exception{
        resource.tokenStore(tokenStore());
    }


    @Bean
    public TokenStore tokenStore(){
        return new JwtTokenStore(jwtAccessTokenConverter());
    }


    @GetMapping("/user/info")
    public Principal user(Principal user){
        return user;
    }

    @PreAuthorize("hasAuthorize('admin')")
    @GetMapping("/admin")
    public String user(){
        return "admin";
    }

    @Bean
    public JwtAccessTokenConverter jwtAccessTokenConverter(){
        JwtAccessTokenConverter jwtAccessTokenConverter = new JwtAccessTokenConverter();
       // jwtAccessTokenConverter.setSigningKey("chuenyee-oauth2.0");
       // String publicKey = ConfigUtil.getProperty("chuenyee.public-key");
        logger.debug("publicKey:"+publicKey);
        jwtAccessTokenConverter.setVerifierKey(publicKey);
        return jwtAccessTokenConverter;
    }

}
